
const _ = require('lodash')
//纯函数缓存
function getArea(r) {
    console.log(r)
    return Math.PI * r * r
}
// 只会打印一次半径 后续调用结果会被缓存
// let getAreaWithMemory=_.memoize(getArea)
// console.log(getAreaWithMemory(4))
// console.log(getAreaWithMemory(4))
// console.log(getAreaWithMemory(4))
//手写memoize方法
function memoize(f) {
    let cache = {}
    return function () {
        let k = JSON.stringify(arguments)
        cache[k] = cache[k] || f.apply(f, arguments)
        return cache[k]
    }
}
let getAreaWithMemory = memoize(getArea)
// console.log(getAreaWithMemory(4))
// console.log(getAreaWithMemory(4))
// console.log(getAreaWithMemory(4))



//柯里化 _.curry(func)
function getSum(a, b, c) {
    return a + b + c
}
const curryed = _.curry(getSum)
// console.log(curryed(1,2,3))
// console.log(curryed(1)(2,3))
// console.log(curryed(1,2)(3))

//柯里化案例 提取字符串中指定内容
// ''.match(/\s+/g)
// ''.match(/\d+/g)

let match = _.curry(function (reg, str) {
    return str.match(reg)
})
const haveSpace = match(/\s+/g)
// console.log(haveSpace('hello world'))

//查询数组原生中含有空字符的原生
// let filter = _.curry(function(fn,array){
//     return array.filter(fn)
// })
let filter = _.curry((fn, array) => array.filter(fn))
const findSpace = filter(haveSpace)
// console.log(findSpace(['cao zy','cao_zy']))

// 手写curry
function curry(func) {
    return function curryFn(...args) {
        //判断实参跟形参的个数
        if (args.length < func.length) {
            return function () {
                return curryFn(...args, ...arguments)
            }
        }
        return func(...args)
    }
}
let myFilter = curry((fn, array) => array.filter(fn))
const myFindSpace = myFilter(haveSpace)
console.log(myFindSpace(['cao zy', 'cao_zy']))